package com.lqian.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * [CyclicBarrier]，一种辅助性的同步结构，允许多个线程等待到达某个屏障
 * 其实反映的是线程并行运行时的协调
 * CyclicBarrier 会自动进行重置
 * @author：Melody_LQ
 * @time：2022/8/29 10:54 上午
 */
public class CyclicBarrierDemo_01 {

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("Action...Go again!");
            }
        });
        for (int i = 0; i <5 ; i++) {
            Thread t = new Thread(new CyclicWorker(barrier));
            t.start();

        }
    }


    static class CyclicWorker implements Runnable{
        private CyclicBarrier barrier;

        public CyclicWorker(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {

                try {
                    for (int i = 0; i <3 ; i++) {
                        System.out.println("Executed!");
                    barrier.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }

        }
    }
}
